#ifndef X11MONITOR_H
#define X11MONITOR_H


#include <QThread>
#include <QMap>
#include <QPoint>
#include <X11/Xlib.h>
#include <X11/extensions/record.h>
#include "IMonitor.h"

// Virtual button codes that are not defined by X11.
// Btn1 -> left
// Btn3 -> right
#define Button1			1
#define Button2			2
#define Button3			3
#define WheelUp			4
#define WheelDown		5
#define WheelLeft		6
#define WheelRight		7
#define XButton1		8
#define XButton2		9

class EventMonitor : public QThread
{
    Q_OBJECT

public:
    EventMonitor(QObject *parent = 0);
    QPoint mousePressPosition;
    QPoint mouseReleasedPosition;

signals:
    void buttonPress(int btn, int x, int y);
    void buttonDrag(int x, int y);
    void buttonRelease(int btn, int x, int y);
    void keyPress(int code);
    void keyRelease(int code);
    void mouseWheel(int x, int y);

protected:
    bool filterWheelEvent(int detail);
    static void callback(XPointer trash, XRecordInterceptData* data);
    void handleRecordEvent(XRecordInterceptData *);
    void run();

private:
    bool isPress;
};


class Xdotool : public IMonitor
{
  public:
    static Xdotool& instance();
    ~Xdotool();
    int getMousePosition(int &root_x, int &root_y);
    unsigned long getActiveWindowPID();
    QString getActiveWindowName();
    QString getProcessPathByPID(unsigned long pid);
    EventMonitor eventMonitor;
    QMap<QString, int> getKeyMap();

    int screenWidth;
    int screenHeight;

    virtual void screenShot() override;
    virtual void stopMonitor() override;

  private:
    Xdotool();
    void initKeyMap();
    Display *display;
    int screen;
    Window root_window;
    unsigned char *prop;
    QMap<QString, int> keyMap;
    void check_status(int status, unsigned long window);
    unsigned char *get_string_property(const char *property_name, Window window);
    unsigned long get_long_property(const char *property_name, Window window);
};




#endif // X11MONITOR_H
